import { Injectable } from '@angular/core';
import { AlgoGraphConfig, AlgoUnitConfig } from './models';

@Injectable()
export class AlgoGraphProcessService {

  constructor() { }

  execute(cfg: AlgoGraphConfig) {
    const startNodes = cfg.Units.filter(a => a.Ports.filter(p => p.Type == "in").length == 0);
    this._ExecuteNodes(cfg, startNodes);
  }

  private _ExecuteNodes(cfg: AlgoGraphConfig, nodes: AlgoUnitConfig[]) {
    nodes.forEach(node => {
      console.log(node.Name, node.Id);
    });
    console.log("--------------------");

    const nextNodes = this._GetNextNodes(cfg, nodes);
    if (nextNodes.length > 0) {
      this._ExecuteNodes(cfg, nextNodes);
    }
  }

  private _GetNextNodes(cfg: AlgoGraphConfig, nodes: AlgoUnitConfig[]) {
    const { Units } = cfg;

    const links = cfg.Links.filter(a => nodes.find(b => b.Id == a.SourceId));
    return Units.filter(a => links.find(b => b.TargetId == a.Id) != null);
  }
}
